package com.mcintyret.site.web.interceptor;

import com.google.common.collect.Maps;
import com.mcintyret.site.context.UserContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * User: mcintyret2
 * Date: 28/03/2012
 */
@Component
public class UserContextInitializationInterceptor extends HandlerInterceptorAdapter {

    private static final String HIT_COUNTER = "hit counter";

    @Resource
    private UserContext userContext;
    @Resource
    private HttpSession httpSession;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof String) {
            // User is not logged in - not much to do here
            userContext.setLoggedIn(false);
        } else if (principal instanceof UserDetails) {
            userContext.setLoggedIn(true);

            UserDetails userDetails = (UserDetails) principal;
            userContext.setUsername(userDetails.getUsername());

            setupHitcountMap(request.getRequestURI());

        } else {
            throw new RuntimeException("Principal is of unsupported type " + principal.getClass());
        }
        return true;
    }

    private void setupHitcountMap(String url) {
        Map<String, Integer> hitCountThisSession = (Map<String, Integer>) httpSession.getAttribute(HIT_COUNTER);
        if (hitCountThisSession == null) {
            hitCountThisSession = Maps.newHashMap();
            httpSession.setAttribute(HIT_COUNTER, hitCountThisSession);
        }
        Integer count = hitCountThisSession.get(url);
        int intCount = count == null ? 1 : count + 1;
        hitCountThisSession.put(url, intCount);

        userContext.setHitsPerPage(hitCountThisSession);

    }
}
